package com.zhentao.map.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zhentao.map.service.MapDeviceService;
import com.zhentao.map.mapper.MapDeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 设备服务实现类
 */
@Service
public class MapDeviceServiceImpl implements MapDeviceService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private MapDeviceMapper mapDeviceMapper;

    @Override
    public Map<String, Object> getLatestWaterQualityDataFromRedis(String deviceId) {
        try {
            // Redis中的key格式，根据实际存储结构调整
            String redisKey = "water_quality_data:" + deviceId;

            // 尝试从Redis获取最新数据
            Object redisData = redisTemplate.opsForValue().get(redisKey);

            if (redisData != null) {
                // 如果Redis中存储的是JSON字符串
                if (redisData instanceof String) {
                    JSONObject jsonData = JSON.parseObject((String) redisData);
                    return convertRedisDataToMap(jsonData);
                }
                // 如果Redis中存储的是对象
                else if (redisData instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> result = (Map<String, Object>) redisData;
                    return result;
                }
            }

            // 如果Redis中没有数据，尝试从数据库获取最新数据
            return getLatestDataFromDatabase(deviceId);

        } catch (Exception e) {
            e.printStackTrace();
            // 如果Redis查询失败，尝试从数据库获取
            return getLatestDataFromDatabase(deviceId);
        }
    }

    /**
     * 将Redis中的JSON数据转换为Map
     */
    private Map<String, Object> convertRedisDataToMap(JSONObject jsonData) {
        Map<String, Object> result = new HashMap<>();

        // 根据你提供的Redis数据结构进行映射
        result.put("ph", parseDouble(jsonData.getString("phValue")));
        result.put("temp", parseDouble(jsonData.getString("temperature")));
        result.put("ntu", parseDouble(jsonData.getString("turbidity")));
        result.put("dataQuality", jsonData.getInteger("dataQuality"));

        // 根据数据质量判断设备状态
        Integer dataQuality = jsonData.getInteger("dataQuality");
        String status = "online";
        if (dataQuality != null && dataQuality == 2) {
            status = "fault";
        }
        result.put("status", status);

        // 添加时间戳
        Object collectTime = jsonData.get("collectTime");
        if (collectTime != null) {
            result.put("timestamp", collectTime.toString());
        }

        // 添加设备ID
        result.put("deviceId", jsonData.getString("deviceId"));

        return result;
    }

    /**
     * 从数据库获取最新数据（备用方案）
     */
    private Map<String, Object> getLatestDataFromDatabase(String deviceId) {
        try {
            // 从数据库获取最新数据
            com.zhentao.pojo.WaterQualityData latestData = mapDeviceMapper.getLatestWaterQualityData(deviceId);
            if (latestData != null) {
                Map<String, Object> result = new HashMap<>();
                result.put("ph", latestData.getPhValue() != null ? parseDouble(latestData.getPhValue()) : 7.12);
                result.put("temp", latestData.getTemperature() != null ? parseDouble(latestData.getTemperature()) : 28.0);
                result.put("ntu", latestData.getTurbidity() != null ? parseDouble(latestData.getTurbidity()) : 0.0);
                result.put("status", latestData.getDataQuality() != null && latestData.getDataQuality() == 2 ? "fault" : "online");
                result.put("deviceId", deviceId);
                result.put("timestamp", latestData.getCollectTime() != null ? latestData.getCollectTime().getTime() : System.currentTimeMillis());
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 如果数据库也没有数据，返回模拟数据
        Map<String, Object> result = new HashMap<>();
        result.put("ph", 7.12);
        result.put("temp", 28.0);
        result.put("ntu", 0.0);
        result.put("status", "online");
        result.put("deviceId", deviceId);
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }

    /**
     * 解析字符串为Double
     */
    private Double parseDouble(String value) {
        try {
            return value != null ? Double.parseDouble(value) : 0.0;
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }

    @Override
    public List<Map<String, Object>> getDeviceList() {
        // 返回设备列表，这里可以根据实际需求从数据库获取
        List<Map<String, Object>> deviceList = new ArrayList<>();

        // 添加监测点001
        Map<String, Object> device001 = new HashMap<>();
        device001.put("id", "ESP8266_001");
        device001.put("name", "监测点001");
        device001.put("location", "保定市莲池区");
        device001.put("latitude", 38.814788);
        device001.put("longitude", 115.489120);
        device001.put("status", "online");
        deviceList.add(device001);

        return deviceList;
    }

    @Override
    public Map<String, Object> getDeviceInfo(String deviceId) {
        Map<String, Object> deviceInfo = new HashMap<>();
        deviceInfo.put("deviceId", deviceId);
        deviceInfo.put("name", "监测点001");
        deviceInfo.put("location", "保定市莲池区");
        deviceInfo.put("latitude", 38.814788);
        deviceInfo.put("longitude", 115.489120);
        deviceInfo.put("status", "online");
        deviceInfo.put("type", "水质监测设备");
        deviceInfo.put("installTime", "2024-01-01");
        return deviceInfo;
    }
}
